<?php
namespace common\models\coin;

use common\models\Common;
use common\models\Functions;
use common\models\Status;
use common\models\user\User;
use common\models\userFund\UserMoneyLog;
use common\services\pay\iosPay\IosPay;
use yii\base\Exception;
use yii\helpers\ArrayHelper;

/**
 * 消息模板
 * Class MessageTemplate
 * @package common\models
 */
class CoinRechargeOrder extends Common
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%coin_recharge_order}}';
    }

    public function getUser() {
        return $this->hasOne(User::className(), ['id' => 'user_id']);
    }

    public function getSetting() {
        return $this->hasOne(CoinRechargeSetting::className(), ['id' => 'setting_id']);
    }

    protected function _createOrderNumber() {
        do {
            $orderNumber = "CO" . date('ymdH') . rand(1000, 9999);
            $where['order_number'] = $orderNumber;
            $exist = static::getCountByWhere($where);
        } while($exist > 0);

        return $orderNumber;
    }

    /**
     * 余额支付成功
     * @param string $orderNumber
     * @param int $totalAmount
     * @param string $payTime
     * @throws Exception
     */
    public function balancePay($orderNumber = '', $totalAmount = 0, $payTime = '') {
        $where['order_number'] = $orderNumber;
        $orderInfo = static::getOneByAndWhere($where);
        $userId = $orderInfo['user_id'];

        //1.判断该订单是否成功支付过
        if ($orderInfo['status'] == Status::COIN_RECHARGE_ORDER_STATUS_DONE) {
            throw new Exception('该订单已经付过款');
        }

//            if ($orderInfo['buy_money'] !== $totalAmount * 100) {
//                throw new Exception('订单金额与实际金额不一致');
//            }

        // 余额信息
        UserMoneyLog::record(
            $userId,
            Status::PROP_TYPE_MONEY,
            Status::MONEY_LOG_TYPE_BUY_COIN,
            -1 * $orderInfo['money'],
            Status::MONEY_LOG_TYPE_MAP[Status::MONEY_LOG_TYPE_BUY_COIN] ?? '',
            '充值金币，单号：【' . $orderNumber.'】',
            $orderInfo['id']
        );

        $this->orderHandle($userId, $orderNumber, Status::PAY_WAY_MONEY, $payTime);

    }


    /**
     * 银行卡支付成功
     * @param string $orderNumber
     * @param int $totalAmount
     * @param string $payTime
     * @return array
     * @throws Exception
     */
    public function bankSuccess($orderNumber = '', $totalAmount = 0, $payTime = '') {
        try {
            $where['order_number'] = $orderNumber;
            $orderInfo = static::getOneByAndWhere($where);
            $userId = $orderInfo['user_id'];

            //1.判断该订单是否成功支付过
            if ($orderInfo['status'] == Status::COIN_RECHARGE_ORDER_STATUS_DONE) {
                throw new Exception('该订单已经付过款');
            }

//            if ($orderInfo['buy_money'] !== $totalAmount) {
//                throw new Exception('订单金额与实际金额不一致');
//            }
            $this->orderHandle($userId, $orderNumber, Status::PAY_WAY_BANK, $payTime);
            return Functions::formatInside(true, '支付成功');
        } catch (Exception  $e) {
            return Functions::formatInside(false, $e->getMessage());
        }
    }

    /**
     * 内购支付
     * @param string $orderNumber
     * @param int $totalAmount
     * @param string $payTime
     * @param string $receiptData
     * @throws Exception
     */
    public function iosPay($orderNumber = '', $totalAmount = 0, $payTime = '', $receiptData = "") {

        $verify = (new IosPay())->verifyPay($receiptData);
        if ($verify['status'] == 0) {
            $where['order_number'] = $orderNumber;
            $orderInfo = static::getOneByAndWhere($where);
            $userId = $orderInfo['user_id'];

            //1.判断该订单是否成功支付过
            if ($orderInfo['status'] == Status::LEVEL_ORDER_STATUS_DONE) {
                throw new Exception('该订单已经付过款');
            }

            //2.是否有内购过
            $isExist = static::getOneByWhere(['transaction_id' => $verify['transaction_id']],['id']);
            if ($isExist) {
                throw new Exception('该订单已经付过款');
            }
//            if ($orderInfo['buy_money'] !== $totalAmount * 100) {
//                throw new Exception('订单金额与实际金额不一致');
//            }

            $this->orderHandle($userId, $orderNumber, Status::PAY_WAY_IOS, $verify['pay_time'], $verify['transaction_id']);
        }
    }

    /**
     * 支付宝支付成功
     * @param string $orderNumber
     * @param int $totalAmount
     * @param string $payTime
     * @return array
     * @throws Exception
     */
    public function aliPaySuccess($orderNumber = '', $totalAmount = 0, $payTime = '') {
        try {
            $where['order_number'] = $orderNumber;
            $orderInfo = static::getOneByAndWhere($where);
            $userId = $orderInfo['user_id'];

            //1.判断该订单是否成功支付过
            if ($orderInfo['status'] == Status::COIN_RECHARGE_ORDER_STATUS_DONE) {
                throw new Exception('该订单已经付过款');
            }

//            if ($orderInfo['buy_money'] !== $totalAmount) {
//                throw new Exception('订单金额与实际金额不一致');
//            }
            $this->orderHandle($userId, $orderNumber, Status::PAY_WAY_BANK, $payTime);
            return Functions::formatInside(true, '支付成功');
        } catch (Exception  $e) {
            return Functions::formatInside(false, $e->getMessage());
        }
    }

    /**
     * 支付成功之后的订单操作
     * @param int $userId
     * @param string $orderNumber
     * @param int $payWay
     * @param string $payTime
     * @param int $iosPayId
     * @throws Exception
     */
    public function orderHandle($userId = 0, $orderNumber = '', $payWay = 0, $payTime = '',$iosPayId = 0) {
        //1.修改订单状态
        $orderInfo = static::getOneByWhere(['order_number' => $orderNumber]);
        $whereUpdate['order_number'] = $orderNumber;
        $update['status'] = Status::COIN_RECHARGE_ORDER_STATUS_DONE;
        $update['pay_time'] = $payTime ? $payTime : date('Y-m-d H:i:s');
        $update['pay_way'] = $payWay;
        if ($payWay == Status::PAY_WAY_IOS) {
            $update['transaction_id'] = $iosPayId;
        }
        $resUpdateOrder = static::updateData($update,$whereUpdate);
        if($resUpdateOrder === false) {
            throw new Exception('更新订单失败');
        }


        // 金币变化
        UserMoneyLog::record(
            $userId,
            Status::PROP_TYPE_COIN,
            Status::COIN_LOG_TYPE_RECHARGE,
            floatval($orderInfo['coin']),
            Status::COIN_LOG_TYPE_MAP[Status::COIN_LOG_TYPE_RECHARGE] ?? '',
            '金币充值',
            $orderInfo['id']
        );

    }
}


